package cn.zhuzicc.reflect;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author zx
 * @version 1.0
 * @className: Test10
 * @description: 分析性能问题
 * @date: 2021/4/28 11:32
 */
public class Test10 {

    public static void main(String[] args) throws Exception {
        test01();
        test02();
        test03();
    }

    /**
     * 普通方式执行
     */
    public static void test01(){
        User user = new User();

        long beginTime = System.currentTimeMillis();
        for (int i = 0; i < 1000000000; i++) {
            user.getName();
        }
        long endTime = System.currentTimeMillis();

        System.out.println("执行10亿个数，普通方式执行：" + (endTime - beginTime) + "ms");
    }

    /**
     * 反射方式执行, 关闭安全检测
     */
    public static void test02() throws Exception {
        User user = new User();
        Class c1 = user.getClass();

        Method getName = c1.getMethod("getName", null);

        long beginTime = System.currentTimeMillis();

        for (int i = 0; i < 1000000000; i++) {
            getName.invoke(user, null);
        }

        long endTime = System.currentTimeMillis();

        System.out.println("执行10亿个数，反射方式执行, 开启安全检测：" + (endTime - beginTime) + "ms");
    }

    /**
     * 反射方式执行, 开启安全检测
     */
    public static void test03() throws Exception {
        User user = new User();
        Class c1 = user.getClass();

        Method getName = c1.getMethod("getName", null);

        long beginTime = System.currentTimeMillis();

        for (int i = 0; i < 1000000000; i++) {
            getName.setAccessible(true);
            getName.invoke(user, null);
        }

        long endTime = System.currentTimeMillis();

        System.out.println("执行10亿个数，反射方式执行, 关闭安全检测：" + (endTime - beginTime) + "ms");
    }
}
